<template>
  <div v-infinite-scroll="getLogList"
       :key="scrollKey"
       infinite-scroll-distance="400"
       :infinite-scroll-disabled="scrollDisabled"
       class="main">
    <div>
      <div v-if="!isSeas && handle && handle.length" class="main-handle">
        <el-button v-for="(item, index) in handle" :key="index"
                   :class="{ 'is-select' : handleType === item.type }"
                   type="primary"
                   @click="handleClick(item.type)">
          {{ item.label }}
        </el-button>
      </div>

      <template v-if="!isSeas && handle && handle.length">
        <LogAdd v-if="!isTaskCreate && canCreateFollowRecord" ref="logAddRef"
                :id="id"
                :show-business="showRelate"
                :show-contacts="showRelate"
                :contacts="contacts"
                :contacts-id="contactsId"
                :follow-types="followTypes"
                :crm-type="crmType"
                class="log-add"
                @send="sendLog"
                @focus="handleType = 'log'"
                @close="handleClick(handleType)"/>

        <TaskQuickAdd v-else ref="taskAddRef"
                      :params="taskParams"
                      :props="taskProps"
                      class="task-quick-add"
                      @focus="handleType = 'task'"
                      @send="refreshLogList"/>
      </template>

      <div :class="{'is-top': handle && handle.length == 0}" class="log">
        <!-- 筛选 -->
        <flexbox justify="flex-end" class="log__header">
          <el-input ref="activitySearchInput" v-model="filterValue.search"
                    placeholder="关键字搜索" prefix-icon="el-icon-search"
                    @keyup.enter="debouncedRefreshLogList(true)"/>
          <time-type-select width="190" :options="timeOptions" :defaultType="filterValue.timeLine"
                            @change="timeTypeChange"/>
          <el-dropdown v-if="typeList.length > 1" trigger="click" @command="handleSelectClick">
            <span class="el-dropdown-link">
              <i :class="['wk', 'dropdown-icon', 'wk-' + activityType.icon]"
                 :style="{ backgroundColor: activityType.color }"/>
              {{ activityType.label }}
              <i class="el-icon-arrow-down el-icon--right"/>
            </span>
            <template v-slot:dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="(item, index) in typeList" :key="index" :command="item">
                  <!--todo whf 这里有个bug，点击下拉框后，左侧的菜单会显示不出来-->
                  <i :class="['wk', 'dropdown-icon', 'wk-' + item.icon]" :style="{ backgroundColor: item.color }"/>
                  {{ item.label }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </flexbox>

        <div v-for="(seciton, secitonIndex) in list" :key="secitonIndex" class="log-section">
          <div class="log-section__title">
            <span class="section-title"><span class="section-title__time">{{ seciton.time }}</span></span>
          </div>
          <template v-for="(item, index) in seciton.list">
            item:{{item}}
            <div v-if="item.type == 1" :class="{ 'only-one': seciton.list.length == 1 }" class="log-cell">
              <LogCell
                  :item="item"
                  :section="secitonIndex"
                  :index="index"
                  :can-delete="!isSeas"
                  @crm-detail="checkCRMDetail"
                  @delete="logCellDelete"
                  @edit="logCellEdit"/>
              <i class="wk wk-message log-cell__mark"/>
            </div>
            <div v-else :class="{ 'only-one': seciton.list.length == 1 }"
                 class="log-cell activity-cell">
              <div v-if="item.type == 2" class="activity-cell">
                <span class="activity-cell__label">
                  {{ item.createTime }}
                  {{ item.realname }}创建了
                  {{ activityTypeHook.getActivityTypeName(item.activityType) }}：
                </span>
                <span class="activity-cell__content"
                      @click="checkCRMDetail(activityTypeHook.getActivityType(item.activityType), item.activityTypeId)">
                  {{ item.activityTypeName || '查看详情' }}
                </span>
              </div>
              <div v-else-if="item.type == 3" class="activity-cell">
                <span class="activity-cell__label">{{ item.createTime }} {{ item.realname }}将商机：</span>
                <span class="activity-cell__content" @click="checkCRMDetail('business', item.activityTypeId)">
                  {{ item.activityTypeName }}
                </span>
                <span>{{ ` 阶段变为 ${item.content}` }}</span>
              </div>
              <LogCell v-else-if="item.type == 4"
                       :item="item"
                       :section="secitonIndex"
                       :index="index"
                       can-delete
                       @crm-detail="checkCRMDetail"
                       @delete="logCellDelete"/>
              <i :class="getActivityIcon(item.activityType)"
                 :style="{ backgroundColor: getActivityTypeColor(item.activityType) }"
                 class="log-cell__mark"
                 style="background-color: #FB9323;"/>
            </div>
          </template>
        </div>
        <p v-if="loading" class="scroll-bottom-tips">加载中...</p>
        <p v-if="noMore" class="scroll-bottom-tips">没有更多了</p>
      </div>
    </div>

    <!-- CRM相关新建 -->
    <CRMAllCreate v-if="isCRMCreate"
                  :crm-type="createCRMType"
                  :action="createActionInfo"
                  @save-success="createCRMSuccess"
                  @close="createCRMClose"/>


    <!-- CRM详情 -->
    <CRMFullScreenDetail :visible="showFullDetail"
                         :crm-type="relationCrmType"
                         :id="relationID"/>

    <!-- 跟进记录编辑 -->
    <LogEditDialog v-model:visible="logEditDialogVisible"
                   :data="logEditData"
                   @save="logEditSave"/>
  </div>
</template>

<script setup>
// todo whf 如果使用了Activity，那么在component中必须设置handle和logTypes
import {useXrSystemIconHook} from '/src/hooks/useXrSystemIconHook.js'
import {useActivityTypeHook} from './useActivityTypeHook.js'
import {computed, getCurrentInstance} from "vue"
import {useErpUserStore} from "@/store/modules/usererp.js";
import {ref, reactive, watch, nextTick, onMounted} from "vue"
//notice next
import LogAdd from './LogAdd.vue'
//notice next
import LogCell from './LogCell.vue'
import LogEditDialog from './LogEditDialog.vue'
import CRMAllCreate from '/src/views/crm/componentsNew/SzCrud/CRMAllCreate.vue'
//notice next
import TaskQuickAdd from '/src/views/taskExamine/task/components/TaskQuickAdd.vue'
import crmTypeModel from '/src/views/crm/model/crmTypeModel.js'

import {objDeepCopy} from '/src/utils/index.js'

import TimeTypeSelect from '/src/szcomponent/TimeTypeSelect/index.vue'
import {debounce} from 'throttle-debounce'
//notice next
import CRMFullScreenDetail from "components/CRMFullScreenDetail.vue";
import {crmCustomerQueryContactsAPI} from '/src/api/crm/customer.js'
import {crmSettingRecordListAPI} from '/src/api/admin/crm.js'
import {
  crmActivityListAPI,
  crmActivityAddAPI
} from '/src/api/crm/common.js'
import {ElMessage} from 'element-plus'

// 引入消息总线
const cxt = getCurrentInstance() //相当于Vue2中的this
const bus = cxt.appContext.config.globalProperties.$bus


defineOptions({
  name: 'ActivitySingle', // 活动
})

const activityTypeHook = useActivityTypeHook()
const xrSystemIconHook = useXrSystemIconHook();

const properties = defineProps({
  // 操作按钮
  handle: {
    type: Array,
    default: () => {
      return []
    }
  },
  // 模块ID
  id: [String, Number],
  // 首要联系人ID
  contactsId: [String, Number],
  // 没有值就是全部类型 有值就是当个类型
  crmType: {
    type: String,
    default: ''
  },
  // 是公海 默认是客户
  isSeas: {
    type: Boolean,
    default: false
  },
  // 筛选数据源
  typeList: {
    type: Array,
    default: () => {
      return []
    }
  },
  // 详情
  detail: {
    type: Object,
    default: () => {
      return {}
    }
  }
})

const loading = ref(false)
// 筛选
const isSearchRequest = ref(false)
const filterValue = ref({})
const timeOptions = reactive([
  {label: '全部', value: ''},
  {label: '最近7天', value: '7'},
  {label: '最近30天', value: '30'},
  {label: '最近60天', value: '60'}
])
const contacts = ref([])
const followTypes = ref([])
const handleType = ref('')
const activityType = ref({
  icon: 'all',
  color: '#2362FB',
  command: '',
  label: '全部活动'
})
// 活动列表
const list = ref([])
const noMore = ref(false)
const page = ref(1)
// 相关新建
const isCRMCreate = ref(false)
const createActionInfo = reactive({type: 'relative', crmType: properties.crmType, data: {}})
const createCRMType = ref('')
// 任务创建
const isTaskCreate = ref(false)
// CRM详情
const showFullDetail = ref(false) // 查看相关客户管理详情
const relationID = ref('',) // 相关ID参数
const relationCrmType = ref('') // 相关类型
const scrollKey = ref(Date.now())
// 跟进记录编辑
const logEditData = ref(null)
const logEditPosition = ref({
  seciton: 0,
  index: 0
})
const logEditDialogVisible = ref(false)
let debouncedRefreshLogList = () => {
  console.log("debouncedRefreshLogList")
} //定义一个空函数

const taskAddRef = ref()
const logAddRef = ref()

watch(properties.id, () => {
  console.log("watch")
  initInfo()
  refreshLogList()
})

function created() {
  debouncedRefreshLogList = debounce(300, refreshLogList)
  initInfo()
}

// created()
onMounted(() => {
  console.log("onMounted")
  created();
})



const crm = computed(() => {
  const erpUserStore = useErpUserStore();
  return erpUserStore.crm
})

// 是否能新建跟进记录
const canCreateFollowRecord = computed(() => {
  return crm.value && crm.value.followRecord && crm.value.followRecord.save
})

const showRelate = computed(() => {
  return properties.crmType == 'customer'
})

const scrollDisabled = computed(() => {
  return loading.value || noMore.value
})

const taskParams = computed(() => {
  const params = {}
  params[`${properties.crmType}Ids`] = properties.id
  return params
})

const taskProps = computed(() => {
  const relatedObj = {}
  relatedObj[properties.crmType] = [properties.detail]
  const relatedObjIds = {}
  relatedObjIds[`${properties.crmType}Ids`] = [properties.id]
  return {
    relatedObj,
    relatedObjIds
  }
})


/**
 * 获取联系人
 */
function getContactsList() {
  crmCustomerQueryContactsAPI({
    customerId: properties.id
  }).then(res => {
    contacts.value = res.data.data.list
  }).catch(() => {
  })
}

/**
 * 发布日志
 */
function sendLog(data) {
  console.log("data", data)
  if (!data.content) {
    // .$message.error('请输入跟进内容')
    ElMessage.error({message: '请输入跟进内容！'})
    return
  }

  const params = {}
  params.activityType = crmTypeModel[properties.crmType]
  params.activityTypeId = data.id
  params.content = data.content
  params.category = data.followType
  const businessIds = data.business.map(item => item.businessId)

  params.batchId = data.batchId
  params.businessIds = businessIds.join(',')
  params.contactsIds = data.contactsId

  params.nextTime = data.nextTime || ''
  params.isEvent = 0
  // todo whf 本组件其实没有使用
  // this.sendLoading = true
  crmActivityAddAPI(params).then(res => {
    // todo whf 本组件其实没有使用
    // this.sendLoading = false
    ElMessage.success({message: '发布成功'})
    // 重置页面
    // if (cxt.refs.logAdd) {
    //   cxt.refs.logAdd.resetInfo()
    // }
    if (logAddRef) {
      logAddRef.value.resetInfo()
    }
    refreshLogList()
  }).catch(() => {
    // todo whf 本组件其实没有使用
    // this.sendLoading = false
  })
}

/**
 * 操作点击
 */
function handleClick(type) {
  console.log("handleClick", type)
  if (handleType.value == type) {
    handleType.value = ''
  } else {
    handleType.value = type
  }

  if (type == 'log') {
    isTaskCreate.value = false
    nextTick(() => {
      if (logAddRef.value) {
        logAddRef.value.value.isUnfold = handleType.value == type
      }
    })
  } else if (type == 'task') {
    isTaskCreate.value = true
    console.log("handleClick2", type)
    nextTick(() => {
      console.log("handleClick3", type)
      // cxt.refs.taskAdd.inputFocus()
      taskAddRef.value.inputFocus()
    })
  } else {
    isTaskCreate.value = false
    const action = {type: 'relative', crmType: properties.crmType, data: {}}
    if (properties.crmType == 'contacts') {
      action.data['customer'] = objDeepCopy(properties.detail)
      // 联系人下新建商机直接关联
      if (type == 'business') {
        action.relativeData = {
          contactsId: properties.detail.contactsId
        }
      }
    } else if (properties.crmType == 'customer') {
      action.data['customer'] = objDeepCopy(properties.detail)
    } else if (properties.crmType == 'business') {
      action.data['customer'] = objDeepCopy(properties.detail)
      action.data['business'] = objDeepCopy(properties.detail)
      // 商机下新建联系人直接关联
      if (type == 'contacts') {
        action.relativeData = {
          businessId: properties.detail.businessId
        }
      }
    } else if (properties.crmType == 'contract') {
      action.data['customer'] = objDeepCopy(properties.detail)
      action.data['contract'] = objDeepCopy(properties.detail)
    }

    // createActionInfo.value = aciton
    createActionInfo.type = action.type
    createActionInfo.crmType = action.crmType
    createActionInfo.data = action.data

    createCRMType.value = type
    isCRMCreate.value = true
  }
}

/**
 * 获取跟进类型详情
 */
function getLogTypeList() {
  crmSettingRecordListAPI().then(res => {
    followTypes.value = res.data.data.map(item => {
      return {
        value: item,
        label: item
      }
    })
  }).catch(() => {
  })
}

/**
 * 初始化信息
 */
function initInfo() {
  nextTick(() => {
    console.log("logAdd")
    console.log("logAdd", logAddRef.value)
    // if (cxt.refs.logAdd) {
    if (logAddRef.value) {
      console.log("initInfo")
      // cxt.refs.logAdd.resetInfo()
      logAddRef.value.resetInfo()
      console.log("initInfo2")
    }

    // 这里会导致getComputedStyle错误
    // console.log("taskAdd")
    // console.log("taskAdd", cxt.refs)
    // console.log("taskAdd", cxt.refs?.taskAdd)
    // if (cxt.refs?.taskAdd) {
    if (taskAddRef.value) {
      // console.log("taskAdd 2", cxt.refs.taskAdd)
      // cxt.refs.taskAdd.resetSendData()
      taskAddRef.value.resetSendData()
    }
  }).then(r => {
  })
  console.log("logAdd 1")
  filterValue.value = {
    search: '',
    timeLine: {
      label: '全部',
      value: ''
    }
  }
  console.log("logAdd 2")
  getLogTypeList()
  console.log("logAdd 3")
  if (showRelate.value) {
    console.log("logAdd 4")
    getContactsList()
    console.log("logAdd 5")
  }
}

/**
 * 初始化日志
 */
function refreshLogList(SearchRequestFlag) {
  console.log("refreshLogList", SearchRequestFlag)
  isSearchRequest.value = SearchRequestFlag || false
  page.value = 1
  noMore.value = false
  list.value = []
  scrollKey.value = Date.now()
  console.log("refreshLogList", page.value, noMore.value, list.value, scrollKey.value)
}

/**
 * 活动筛选
 */
function handleSelectClick(value) {
  activityType.value = value
  refreshLogList()
}

/**
 * 时间筛选
 */
function timeTypeChange(data) {
  filterValue.value.timeLine = data
  refreshLogList()
}

/**
 * 活动日志
 */
function getLogList() {
  console.log("getLogList")
  loading.value = true
  const params = {
    page: page.value,
    crmType: crmTypeModel[properties.crmType], // 9是公海
    activityType: activityType.value.command,
    activityTypeId: properties.id
  }

  console.log("getLogList 1")
  if (filterValue.value.search) {
    params.search = filterValue.value.search
  }
  console.log("getLogList 2")
  if (filterValue.value.timeLine.type) {
    if (filterValue.value.timeLine.type === 'custom') {
      params.startDate = filterValue.value.timeLine.startTime.replace(/\./g, '-')
      params.endDate = filterValue.value.timeLine.endTime.replace(/\./g, '-')
    } else {
      params.intervalDay = filterValue.value.timeLine.value || ''
    }
  }
  console.log("getLogList 3")
  crmActivityListAPI(params).then(res => {
    console.log("getLogList 5")
    console.log("getLogList 5", res)
    console.log("getLogList 5", res.data.data)
    loading.value = false
    if (!noMore.value) {
      console.log("getLogList 6")
      page.value++
      if (list.value.length) {
        console.log("getLogList 7")
        const lastLog = list.value[list.value.length - 1]
        if (res.data.data.time && res.data.data.list.length && lastLog.time != res.data.data.time) {
          list.value.push(res.data.data)
        }
      } else {
        console.log("getLogList 8")
        console.log("getLogList 8", res.data.data)
        if (res.data.data.time && res.data.data.list.length) {
          list.value.push(res.data.data)
        }
        console.log("getLogList 8", list.value)
      }
    }
    noMore.value = res.data.data.lastPage
    if (isSearchRequest.value) {
      console.log("getLogList 9")
      nextTick(() => {
        cxt.refs.activitySearchInput.focus()
      })
    }
  }).catch(() => {
    console.log("getLogList 4")
    noMore.value = true
    loading.value = false
  })
  console.log("getLogList 4")
}

/**
 * CRM新建成功
 */
function createCRMSuccess() {
  handleType.value = ''
  refreshLogList()
}

function createCRMClose() {
  isCRMCreate.value = false
  handleType.value = ''
}

/**
 * 跟进日志查看详情
 */
function checkCRMDetail(type, id) {
  relationID.value = id
  relationCrmType.value = type
  showFullDetail.value = true
}

function getActivityIcon(activityType) {
  // 1 线索 2 客户 3 联系人 4 产品 5 商机 6 合同 7 回款 8 日志 9 审批 10 日程 11 任务 12 发邮件
  return xrSystemIconHook.getXrIcon(activityTypeHook.getActivityType(activityType))
}

function getActivityTypeColor(activityType) {
  // 1 线索 2 客户 3 联系人 4 产品 5 商机 6 合同 7 回款 8 日志 9 审批 10 日程 11 任务 12 发邮件
  return xrSystemIconHook.getXrIconColor(activityTypeHook.getActivityType(activityType))
}

/**
 * 跟进日志删除
 */
function logCellDelete(data, index, seciton) {
  list.value[seciton].list.value.splice(index, 1)
  if (list.value[seciton].list.length == 0) {
    list.value.splice(seciton, 1)
  }
  scrollKey.value = Date.now()
}

/**
 * 跟进日志编辑
 */
function logCellEdit(data, index, seciton) {
  logEditData.value = data
  logEditPosition.value = {
    seciton,
    index
  }
  logEditDialogVisible.value = true
}

function logEditSave(data) {
  if (logEditPosition.value.seciton >= 0 && logEditPosition.value.index >= 0) {
    list.value[logEditPosition.value.seciton].list.splice(logEditPosition.value.index, 1, data)
  }
}

</script>


<style scoped lang="scss">
.main {
  height: 100%;
  position: relative;
  overflow: auto;
  padding: 15px;

  &-handle {
    // 新建按钮
    .el-button {
      margin-bottom: 5px;
      padding: 6px;
      font-size: 12px;
      color: #666;
      background-color: #f1f5fd;
      border-color: #f1f5fd;

      :deep(i) {
        font-size: 13px;
      }
    }

    .el-button:first-child {
      margin-right: 10px;
    }

    .el-button + .el-button {
      margin-left: 0;
      margin-right: 10px;
    }

    .el-button--primary:hover {
      background: $xr-color-primary;
      border-color: $xr-color-primary;
      color: #ffffff;
    }

    .el-button.is-select {
      background: $xr-color-primary;
      border-color: $xr-color-primary;
      color: #ffffff;
    }
  }
}

.scroll-div {
  height: 200px;
  background-color: red;
  margin-top: 20px;
}

.task-quick-add,
.log-add {
  margin-top: 15px;
}

.log.is-top {
  margin-top: 0;
}

.log {
  margin-top: 20px;
  position: relative;

  &__header {
    height: 40px;
    margin-bottom: 10px;

    .el-input {
      width: 150px;
      margin-right: 10px;

      :deep(input) {
        height: 30px;
        line-height: 30px;
      }
    }

    .time-type-select {
      :deep(.type-select) {
        input {
          height: 30px;
          line-height: 30px;
        }
      }
    }
  }

  &-section {
    &__title {
      padding: 8px 0;

      .section-title {
        background-color: #f1f5fd;
        color: white;
        font-size: 12px;
        padding: 4px 10px;
        height: 20px;
        border-radius: 15px;

        &__time {
          color: #666;
          font-weight: 600;

          &::before {
            content: ' ';
            position: relative;
            width: 6px;
            height: 6px;
            border-radius: 3px;
            background-color: #666;
            margin-right: 5px;
            bottom: 2px;
            display: inline-block;
          }
        }
      }
    }
  }

  &-cell {
    margin-left: 30px;
    padding: 8px;
    position: relative;

    &__mark {
      position: absolute;
      left: -10px;
      top: 24px;
      background-color: #487dff;
      color: white;
      border-radius: $xr-border-radius-base;
      padding: 4px;
      font-size: 12px;
      z-index: 1;
    }
  }

  // 仅仅一个
  &-cell.only-one::before {
    display: none;
  }

  // 活动cell
  &-cell.activity-cell {
    .log-cell__mark {
      top: 6px;
    }
  }

  &-cell::before {
    position: absolute;
    content: ' ';
    width: 1px;
    top: 0;
    left: 0;
    bottom: 0;
    background-color: $xr-border-line-color;
  }

  &-cell:nth-child(2)::before {
    top: 24px;
  }

  &-cell:last-child::before {
    height: 40px;
  }

  &-cell.activity-cell:last-child::before {
    height: 20px;
  }
}

.activity-cell {
  font-size: 12px;
  padding: 5px 13px;

  &__label {
    color: #666666;
  }

  &__content {
    cursor: pointer;
    color: $xr-color-primary;
  }

  &__content:hover {
    text-decoration: underline;
  }
}

// 下拉筛选效果
// .tabs-head-select {
//   position: absolute;
//   top: 0;
//   right: 15px;
// }

.el-dropdown-link {
  cursor: pointer;
  color: #333333;

  .el-icon--right {
    color: #666666;
  }
}

.dropdown-icon {
  color: white;
  margin-right: 5px;
  padding: 3px;
  font-size: 12px;
  border-radius: $xr-border-radius-base;
}
</style>
